import request from "@/utils/request";
//import request from '@/utils/request-mock'
import settings from "@/settings";
import { ossDownload } from "@/api/public";

//import { Link } from 'element-ui'

/**
 * @description 统一导出excel方法
 */

export const exportExcel = (
  url,
  params,
  method = "get",
  excelName = "数据导出",
  suffix = "xls",
  isOss = true
) => {
  const options = {
    url,
    method,
  };
  // if (Cookies.get('token')) {
  //   options.headers = {
  //     Authorization: Cookies.get('token')
  //   }
  // }
  if (options.method.toLocaleLowerCase() === "get") {
    options.params = params;
  } else {
    options.data = params;
  }
  return new Promise((resolve, reject) => {
    request(options)
      .then((res) => {
        /* 兼容ie内核 360浏览器的兼容模式 */
        if (res.result == 0) {
          if (isOss) {
            var downloadElement = document.createElement("a");
            var href = settings.moudelUrl + res.data.url;
            downloadElement.href = href;
            // document.body.appendChild(downloadElement)
            // let fileNames = res.data.url.split("/")
            // downloadElement.download = fileNames[fileNames.length-1]
            downloadElement.click();
            // document.body.removeChild(downloadElement)
            // window.URL.revokeObjectURL(href)
          } else {
            const { url: fileUrl } = res.data;

            let fileName = "";
            try {
              const tempUrl = fileUrl.split("/");
              const url = tempUrl[tempUrl.length - 1];
              fileName = url.slice(0, url.lastIndexOf("."));
            } catch (error) {}

            exportFile("base64")({
              url: fileUrl,
              fileName,
              fileType: "xlsx",
            });
          }
        }

        resolve(res);
      })
      .catch((err) => {
        const message = err || "导出失败，请稍后重试";
        reject(message);
      });
  });
};

/**
 MIME映射表 下面链接可查看
 URL: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
 */
const MIME_MAP = {
  zip: "application/zip",
  xml: "text/xml",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xls: "application/vnd.ms-excel",
  txt: "text/plain",
  pdf: "application/pdf",
  png: "image/png",
  mp3: "audio/mpeg",
  json: "application/json",
  js: "text/javascript",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  html: "text/html",
  gif: "image/gif",
};

/**
 * base64类型 文件导出
 * @param {url, fileType, fileName} options
 * @url oss文件路径
 * @fileType  文件类型
 * @fileName  文件名
 */
const base64Export = async (options) => {
  const { url, fileType, fileName } = options;
  const res = await ossDownload({
    templateFilePath: url,
  });
  const { data } = res;

  let file = base64ToBlob(data, MIME_MAP[fileType]);

  const blob = file;
  let link = document.createElement("a");
  link.href = URL.createObjectURL(
    new Blob([blob], { type: MIME_MAP[fileType] })
  );
  link.download = fileName;

  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href);
};

/**普通导出 */
const hrefExport = (options) => {
  const { url } = options;
  window.location.href = settings.moudelUrl + url;
};

/**
 *
 * @param {导出函数类型} type
 * @returns
 */
export const exportFile = (type = "href") => {
  switch (type) {
    case "href": // domain + url 导出
      return hrefExport;
    case "base64": // base64 导出
      return base64Export;
    default:
      return hrefExport;
  }
};

/**
 * base64转blob类型
 * @param {base字符串} base64Str
 * @returns Bolb
 */
const base64ToBlob = (base64Str, type) => {
  let buffer = Buffer.from(base64Str, "base64");
  return new Blob([buffer], { type: type });
};
